/**
 * ListCategoriesPane.java
 * @author: liuex
 * 2008-1-9 ����08:07:31
 *
 * note: 
 */
package org.lex.swing.prefs.old;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.Timer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.lex.swing.Swings;
import org.lex.swing.prefs.CategoriesModel;
import org.lex.swing.prefs.Category;
import org.lex.swing.prefs.FontCategory;
import org.lex.swing.prefs.TestCategory;
import org.lex.utils.BinarySearch;
import org.lex.utils.text.Chars;


public class ListCategoriesPane extends CategoriesModel {
	private JList categoriesList = null;
	private DefaultListModel listModel = null;

	public static void main(String[] args) {
		final ListCategoriesPane list = new ListCategoriesPane();
		list.addCategories(new FontCategory());
		Swings.show(list);
		new Timer(1000, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				list.addCategories(new TestCategory(Chars.randomString()));
			}
		}).start();
	}

	public ListCategoriesPane() {
		super();
		this.initialize();
	}

	public void addCategories(Category... categories) {
		if (null == categories || 0 == categories.length)
			return;

		for (Category catalog : categories) {
			String title = catalog.getTitle();
			int pos = BinarySearch.search(listModel, title);
			if (pos < 0)
				pos = -1 - pos;
			else
				System.err.println("[" + title + "] already in list ");
			listModel.insertElementAt(title, pos);
		}
	}

	private void initialize() {
		this.setLayout(new BorderLayout());
		JScrollPane scrollPane = new JScrollPane(this.getCategoriesList());
		this.add(scrollPane, BorderLayout.CENTER);
	}

	private JList getCategoriesList() {
		if (null == categoriesList) {
			categoriesList = new JList(this.getListModel());
			// list = new JList( new String[]{ "1", "2", "a" } );
			categoriesList.setBorder(BorderFactory.createEmptyBorder());
			categoriesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			categoriesList.addListSelectionListener(new ListSelectionListener() {
				public void valueChanged(ListSelectionEvent e) {
					if (true == e.getValueIsAdjusting())
						return;
					Object title = categoriesList.getSelectedValue();
					if (null == title)
						return;
					fireSelectedCategoryChanged(title.toString());
				}
			});
		}
		return categoriesList;
	}

	private DefaultListModel getListModel() {
		if (null == listModel)
			listModel = new DefaultListModel();
		return listModel;
	}
}
